package cn.com.headfree.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.gta.edu.sdk.util.StringUtil;

import cn.com.headfree.base.controller.ExBaseController;
import cn.com.headfree.entity.isc.User;
import cn.com.headfree.loginmes.service.ILoginMesService;
import cn.com.headfree.loginmes.util.NetworkUtil;
import cn.com.headfree.util.RedisClusterUtil;
import net.sf.json.JSONObject;

//@Component
@WebFilter(urlPatterns = "/*", filterName = "loginMesFilter")
public class LoginFilter extends ExBaseController implements Filter {

	private static final Logger LOG = LogManager.getLogger(LoginFilter.class);

//	@Value("${login_ip}")
//	private String login_ip;

	@Autowired
	private ILoginMesService loginMesService;

	private static final Set<String> ALLOWED_PATHS = Collections
			.unmodifiableSet(new HashSet<>(Arrays.asList("/version/getNotice","/static","/comm-front-frame","/loginMes")));

	private static Object lock=new Object();

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest re = (HttpServletRequest) request;


		String path = re.getRequestURI().substring(re.getContextPath().length()).replaceAll("[/]+$", "");

		LOG.info("-------------------------------------------------------成功进入LoginFilter方法...，path="+path);
		chain.doFilter(request, response);

		//记录用户登录，只为记录登录数，不在乎真实用户信息
		// 获取登陆用户的真实ip
		String loginIp = NetworkUtil.getIpAddress(re);
		User user = new User();
		user.setFax("1111");
		user.setName("虚拟登录用户");
		user.setBaseOrgId("11111");
		user.setBaseOrgName("虚拟部门");
		try {
			loginMesService.addLoginMes(user, loginIp);
			LOG.info("登陆用户信息入库成功！");
		} catch (Exception e) {
			LOG.error("登陆用户信息入库失败！", e);
		}
		/*boolean allowedPath = ALLOWED_PATHS.contains(path);

		if (allowedPath) {
			System.out.println("*******************************************************这里是不需要处理的url进入的方法，path="+path);
			chain.doFilter(request, response);
		} else {
			synchronized(lock) {
			User user = this.getLoginUserInfo(re);
			String loginUserStr = RedisClusterUtil.getInstance().getString("login-user-" + user.getFax());
			if (StringUtil.isNullOrEmpty(loginUserStr)) {
				// 获取登陆用户的真实ip
				String loginIp = NetworkUtil.getIpAddress(re);
				try {
					loginMesService.addLoginMes(user, loginIp);
					LOG.info("登陆用户信息入库成功！");
				} catch (Exception e) {
					LOG.error("登陆用户信息入库失败！", e);
				}
			}

			// 获取redis里面存在的登陆用户数据
//		String jsonStr = RedisClusterUtil.getInstance().getString("loginUser");

//		LOG.info("登陆前redis里面存在的登陆用户数据:" + jsonStr);
//		Map<String, User> map = new HashMap<String, User>();
//		if(!StringUtil.isNullOrEmpty(jsonStr)) {
//			map = JSON.parseObject(jsonStr, Map.class);
//		}else {
//			map=new HashMap<String,User>();
//		}
//		map.put(user.getFax(), user);
//		// 重新赋值
//		String newJsonStr = JSON.toJSON(map).toString();
//		RedisClusterUtil.getInstance().setString("loginUser", newJsonStr, 2 * 60 * 1000);
//
//		LOG.info("............登陆后redis里面存在的登陆用户数据:" + RedisClusterUtil.getInstance().getString("loginUser"));
			JSONObject JSONStr = JSONObject.fromObject(user);
			String userStr = JSONStr.toString();
			RedisClusterUtil.getInstance().setString("login-user-" + user.getFax(), userStr, 2 * 60);

			LOG.info("=============================="
					+ RedisClusterUtil.getInstance().getString("login-user-" + user.getFax()));
			LOG.info("=============================="
					+ Arrays.toString(RedisClusterUtil.getInstance().keys("login-user-*").toArray()));

			chain.doFilter(request, response);
			}
		}*/
	}
}
